package io.gitee.mayan50.autoassociate.util;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.stream.Stream;

public class FieldUtils {

    public static Type getFieldGenericType(Field field) {
        Type type = field.getGenericType();
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type[] argumentsTypes = parameterizedType.getActualTypeArguments();
        if (argumentsTypes.length == 0) return null;
        return argumentsTypes[0];
    }

    public static Type getClassGenericType(Class<?> clazz) {
        Type[] types = clazz.getGenericInterfaces();
        if (types.length == 0) return null;
        ParameterizedType parameterizedType = (ParameterizedType) types[0];
        Type[] argumentsTypes = parameterizedType.getActualTypeArguments();
        if (argumentsTypes.length == 0) return null;
        return argumentsTypes[0];
    }

    public static Field[] getField(Class<?> entityClass) {
        Class<?> superClass = entityClass.getSuperclass();
        if (superClass != null) return Stream.concat(Stream.of(entityClass.getDeclaredFields()), Stream.of(superClass.getDeclaredFields())).toArray(Field[]::new);
        return entityClass.getDeclaredFields();
    }

    public static Field getColumnField(Class<?> entityClass, String column) throws NoSuchFieldException {
        return entityClass.getDeclaredField(StrUtils.humpToLine(column));
    }

}
